package com.example.adminLite.service;

import com.example.adminLite.exception.WebRunException;
import com.example.adminLite.model.MusicType;
import com.example.adminLite.repository.MusicTypeRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class MusicTypeService{

    private final MusicTypeRepository musicTypeRepository;

    public MusicTypeService(MusicTypeRepository musicTypeRepository) {
        this.musicTypeRepository = musicTypeRepository;
    }

    public MusicType save(MusicType musicType)
    {
         MusicType existMusicType = this.musicTypeRepository.findMusicTypeByMusicTypeName(musicType.getMusicTypeName());
         if (!Objects.isNull(existMusicType) && !Objects.equals(existMusicType.getId(), musicType.getId())){
             throw new WebRunException("歌曲名已经存在");
         }
        return this.musicTypeRepository.save(musicType);
    }

    public List<MusicType> index()
    {
        return this.musicTypeRepository.findAll();
    }

    public void del(long id) {
        this.musicTypeRepository.deleteById(id);
    }

    public MusicType findById(long id) {
        Optional<MusicType> byId = this.musicTypeRepository.findById(id);
        return byId.orElse(null);
    }
}
